/**
 * Created by bean^
 * User: bean_4@163.com
 * Date: DATE
 * Time: TIME
 *
 */
const handel = (data) => {
  return data.map(item => {
    const {
      county,
      countyCode,
      provinceCode,
      cityCode
    } = item
    return {
      value: countyCode,
      label: county,
      parentId: cityCode || provinceCode || 0,
      provinceCode,
      isDone: !!cityCode, // 是最低级别
      isHas: false// 是否已经被挂载到tree
    }
  })
}
const formatArea = (data) => {
  if (!Array.isArray(data) || !data.length) return []
  return angryTree(handel(data), 0)
}

let has
const arrangeTree = (tags = [], tree = []) => {
  if (has == tags.length) return
  tree.forEach(item => {
    item.isHas = true
    if (!item.isDone) { // 是最低级别不再查找children
      let _children = formatList(tags, item.value)
      if (_children.length) {
        item.children = _children
        has += _children.length
        arrangeTree(tags, _children)
      }
    }
  })
  tags = tags.filter(item => !item.isHas)
  return tags
}

const formatList = (list = [], id) => {
  return list.filter(it => it.parentId === id)
  // const currList = list.filter(it => it.parentId === id)
  // return currList.length ? currList : list.filter(it => it.provinceCode === id)//处理北京市无市辖区一级的问题
}

const angryTree = (list = [], id) => {
  let bean = formatList(list, id)
  has = bean.length
  let tags = arrangeTree(list, bean)
  tags.forEach(tag => {
    const target = bean.find(item => tag.provinceCode === item.value)
    if (target) {
      if (target.children) {
        target.children.push(tag)
      } else {
        target.children = [tag]
      }
      tag.isHas = true
    }
  })
  return bean
}

export default formatArea
